/*
 * @(#)FirstTag.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.web.taglibs.pager;

import java.text.MessageFormat;

import javax.servlet.jsp.JspWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.usf.core.config.PagerConfigInfo;
import com.nhncorp.usf.core.config.PagerConfigInfos;
import com.nhncorp.usf.core.result.template.directive.PagerInfo;

/**
 * 처음 위치로 이동하기 위한 {@link PagerTag}.
 *
 * @author Web Platform Development Team
 */
public class FirstTag extends PagerTag {
	static final long serialVersionUID = 8932197229265080374L;

	static Log log = LogFactory.getLog(FirstTag.class);

	public FirstTag() {
	}

	public FirstTag(String... appendings) {
		super(appendings);
	}

	/**
	 * {@inheritDoc}
	 * */
	protected void generate(NavigatorTag parent, PagerInfo pagerInfo) throws Exception {

		PagerConfigInfo pagerConfig = PagerConfigInfos.get(parent.pagerType);
		
		if (pagerConfig == null) {
			throw new IllegalArgumentException("failed to find pager config for type '" + parent.pagerType + "'");
		}
		
		JspWriter out = pageContext.getOut();

		if (parent.page == 1) {
			String firstOff = pagerConfig.getFirstOff();
			out.print(resolve(firstOff, pagerConfig.getDataHandlerName()));
		} else {
			String queryString = getQueryString(pagerInfo);
			String startTag = getStartTag(parent, queryString, 1, pagerConfig.getFirstAtagAttribute());
			String endTag = END_ATAG;

			String first = pagerConfig.getFirst();
			String preMessage = resolve(first, pagerConfig.getDataHandlerName());
			out.println(MessageFormat.format(preMessage, startTag, endTag, parent.firstPage));
		}
	}

	/**
	 * {@inheritDoc}
	 * */
	protected void failed(Exception ex) {
		log.error(ex);
	}
}